# -*- coding: UTF-8 -*-
# Author:     yucheng
# CreateTime: 2018/6/11 17:23


import os

from flask import Flask, render_template


def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('/error/404.html'), 404

    @app.errorhandler(403)
    def user_not_access(e):
        return render_template('/error/403.html'), 403

    app.register_error_handler(404, page_not_found)
    app.register_error_handler(403, user_not_access)

    from . import db
    db.init_app(app)

    from . import auth
    app.register_blueprint(auth.bp)

    from . import blog
    app.register_blueprint(blog.bp)
    app.add_url_rule('/', endpoint='index')

    return app


"""
app.instance_path 在 'E:\\learn\\python\\flsak_demo\\instance'
"""
